package Login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-25
 * Time: 13:22
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //前端发送post方法提交，用户名，密码到后端来
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //验证用户名和密码是否正确，这里直接写死
        if (!username.equals("zhangsan") && !username.equals("lisi")) {
            //登录失败
            System.out.println("登录失败，用户名错误!");
            resp.sendRedirect("login.html");
            return;
        }
        if (!password.equals("123123")) {
            //登录失败
            System.out.println("登录失败，密码错误!");
            resp.sendRedirect("login.html");//设置url的
            return;
        }
        //登录成功 创建session对象
        HttpSession session = req.getSession(true);//为true，存在就返回，不存在就创建session
        session.setAttribute("username", username);
        resp.sendRedirect("index");
    }
}
